package cn.itrip.auth.controller;

import cn.itrip.auth.exception.RedisException;
import cn.itrip.auth.exception.TokenProtectedException;
import cn.itrip.auth.service.TokenService;
import cn.itrip.auth.service.UserService;
import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.beans.vo.ItripTokenVO;
import cn.itrip.beans.vo.ItripWechatTokenVO;
import cn.itrip.common.DtoUtil;
import cn.itrip.common.ErrorCode;
import cn.itrip.common.MD5;
import cn.itrip.common.UrlUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @ClassName WxController
 * @Description TODO
 * @Author yaozhaobao
 * @Date 2020/12/16 11:44
 * @Version 1.0
 **/
@RestController
@RequestMapping("/vx")
public class WxController {
    String appid ="wxb26911937eb6a115";
    String appSecret="9e73612b9fc855911dbe0df27173411a";

    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;



    /**
     * 前端有一个微信登录的小按钮,发送微信登录请求
     * @param response
     */
    @RequestMapping(value="/wechat/login",method = RequestMethod.GET)
    public void  wechatlogin(HttpServletResponse response, HttpServletRequest request) throws IOException {

        String redirest_url="http://127.0.0.1:8080/auth/vx/wechat/callback";
        String str=MD5.getMd5(request.getHeader("user-agent"),6);   //a9bc50
        System.out.println(str);
        //发送一个请求微信授权的页面
        /**
         * 请求平台授权登录
         */
        String agent=request.getHeader("user-agent");
        String code=MD5.getMd5(agent,6);
        System.out.println("============"+code);
        String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
                appid+"&redirect_uri=" +
                URLEncoder.encode(redirest_url,"UTF-8")
                +"&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=yaozhaobao_" +
                str+"_#wechat_redirect";

        //发送请求给微信平台
        response.sendRedirect(url);
    }


    /**
     * 微信平台当用户手动授权后回调的接口
     * @param code  临时票据 拿着个临时票据换取access_token
     * @param state 安全校验，保证请求是微信平台过来的，验签
     * @return
     */
    @RequestMapping(value = "/wechat/callback",method = RequestMethod.GET)
    public Dto wechatCallBack(@RequestParam String code,@RequestParam String state) throws Exception {
        System.out.println("==========================="+state.split("_")[1]);
        if(!state.split("_")[0].equals("yaozhaobao")){
            return DtoUtil.returnFail("非法请求", ErrorCode.AUTH_ILLEGAL_USERCODE);
        }
        if(code==null){
            return  DtoUtil.returnFail("用户没有授权",ErrorCode.AUTH_AUTHENTICATION_FAILED);
        }
        //联合Code appid,appsecret发送http  get请求,返回access-Token

        String uri="https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +
                appid+"&secret=" +
                appSecret+"&code=" +
                code+"&grant_type=authorization_code";
        System.out.println(uri);
        //发送一个http请求 URlUtil.loadURL  代码发送http请求
        String result= UrlUtils.loadURL(uri);
        System.out.println(result);
        //json字符串---》Map
        Map map= JSON.parseObject(result, Map.class);
        //判断请求是否成功获取到access-token
        if(map.get("errorCode")!=null){
            return DtoUtil.returnFail("没获取到token,发生错误",ErrorCode.AUTH_AUTHENTICATION_FAILED);
        }
        System.out.println( "access_token============="+map.get("access_token").toString());
        //判断这个用户是否第一次登陆,若是第一次登陆则需要把用户的信息保存到数据库表中（注册）
        ItripUser itripUser= userService.getUserByUserCode(map.get("openid").toString());
        if( itripUser==null){
            //第一次登陆
            itripUser = new ItripUser();
            itripUser.setActivated(1);
            itripUser.setUserCode(map.get("openid").toString());
            itripUser.setUserName(map.get("openid").toString());
            itripUser.setCreationDate(new Date());
            itripUser.setUserType(1);
            userService.itripxAddUserByPhone(itripUser);
        };
        //accessToken 令牌是微信给平台
        //token   我们平台给用户
        String token =tokenService.genarateToken2(state.split("_")[1],itripUser);
        //保存token
        tokenService.saveToken(token,itripUser);
        //5.返回token到客户端 返回token，生成token时间 token过期时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = simpleDateFormat.parse(token.split("-")[3]);
        long gen= date.getTime();
        long expire=date.getTime()+TokenService.TOKEN_TIMEOUT;

        ItripWechatTokenVO itripWechatTokenVO = new ItripWechatTokenVO(token,expire,gen);
        itripWechatTokenVO.setAccessToken(map.get("access_token").toString());
        itripWechatTokenVO.setOpenid(map.get("openid").toString());
        itripWechatTokenVO.setExpiresIn(map.get("expires_in").toString());
        itripWechatTokenVO.setRefreshToken(map.get("refresh_token").toString());
        System.out.println("==================refresh_token:"+map.get("refresh_token").toString());
        System.out.println("==================token:"+token);
        return DtoUtil.returnDataSuccess(itripWechatTokenVO);
    }



    @RequestMapping(value="/wechat/token/refresh",method = RequestMethod.GET)
    public Dto refreshWechatToken(HttpServletRequest request,@RequestParam  String token,@RequestParam String refreshtoken2){
            //刷新平台token,查看是否在置换期
        //获取token agent                                 //6f34d0
        String agent=request.getHeader("user-agent");
        System.out.println("============"+MD5.getMd5(request.getHeader("user-agent"),6));  //   //a9bc50
        System.out.println("============="+agent+"===========================");
        ItripTokenVO itripTokenVO = null;
        //获取前端的token  agent校验用户是否有效
        if(tokenService.validateToken(token,agent)) {
            //置换token
            try {
                itripTokenVO= tokenService.refreshToken(token,agent);
            } catch (TokenProtectedException e) {
                e.printStackTrace();
                return DtoUtil.returnFail("还在保护器",ErrorCode.AUTH_PROTECTTIME_ERROR);
            } catch (ParseException e) {
                e.printStackTrace();
                return   DtoUtil.returnFail("日期转换异常",ErrorCode.AUTH_UNKNOWN);
            } catch (RedisException e) {
                e.printStackTrace();
                return  DtoUtil.returnFail(e.getMessage(),ErrorCode.AUTH_REDIS_ERROR);
            }

        }else{
            return  DtoUtil.returnFail("token无效",ErrorCode.AUTH_TOKEN_INVALID);
        }

        //刷新微信平台的accesstoken
        //请求微信平台置换token
        String uri="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="+appid+"&grant_type=refresh_token&refresh_token="+refreshtoken2;
        String result= UrlUtils.loadURL(uri);
        Map map= JSON.parseObject(result, Map.class);
        //判断请求是否成功获取到access-token
        if(map.get("errorCode")!=null){
            return DtoUtil.returnFail("没获取到token,发生错误",ErrorCode.AUTH_AUTHENTICATION_FAILED);
        }
        //封装我们平台的token到这个类里面ItripWechatTokenVO
        ItripWechatTokenVO itripWechatTokenVO = new ItripWechatTokenVO(itripTokenVO.getToken(),itripTokenVO.getExpTime(),itripTokenVO.getGenTime());
        //封装微信平台置换的accesstoken到ItripWechatTokenVO
        itripWechatTokenVO.setAccessToken(map.get("access_token").toString());
        itripWechatTokenVO.setOpenid(map.get("openid").toString());
        itripWechatTokenVO.setExpiresIn(map.get("expires_in").toString());
        itripWechatTokenVO.setRefreshToken(map.get("refresh_token").toString());

       return DtoUtil.returnDataSuccess(itripWechatTokenVO);

    }


    @RequestMapping(value = "/wechat/user/info",method = RequestMethod.GET)
    public Dto getUserInfo(String accesstoken,String openId) throws UnsupportedEncodingException {
        String url ="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accesstoken+"&openid="+openId+"&lang=zh_CN";
       //http请求
        String result =UrlUtils.loadURL(url);
        result=new String(result.getBytes("GBK"),"UTF-8");
        System.out.println(result);
        Map map = JSON.parseObject(result,Map.class);
          return DtoUtil.returnDataSuccess(map);
    };






}
